﻿using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace vBridge.Wpf.ValueConverters
{
    public sealed class BitmapToBitmapSourceValueConverter : ValueConverterBase<Bitmap, BitmapSource>
    {
        protected override BitmapSource SourceToDestination(Bitmap value, Type targetType, Object parameter,
            CultureInfo culture)
        {
            if (value == null)
                return null;
            BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                value.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            return bitmapSource;
        }

        protected override Bitmap DestinationToSource(BitmapSource value, Type targetType, Object parameter,
            CultureInfo culture)
        {
            if (value == null)
                return null;

            using (var outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(value));
                enc.Save(outStream);
                var bitmap = new Bitmap(outStream);

                return new Bitmap(bitmap);
            }
        }
    }
}